package com.rui.study.algorithm.P_动态规划_nxn矩阵最短路径;

import java.util.Random;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-01-03 15:13
 **/
public class Solution2回溯法_状态表 {

    private static final int N = 100;

    private int min = Integer.MAX_VALUE;

    private Integer[][] state = new Integer[N][N];

    public void minDist(int[][] w, int n, int i, int j, int dist) {
        if (i == n && j == n) {
            if (dist < min) min = dist;
            return;
        }

        if (state[i][j] != null) {
            if (state[i][j] <= dist) {
                return;             // 当前状态的dist更大，无需往下走
            } else {
                state[i][j] = dist; // 当前状态的dist更小，继续往下走
            }
        } else {
            state[i][j] = dist;     // 第一次记录当前状态dist
        }

        if (i < n) {// 往下走
            minDist(w, n, i+1, j, dist + w[i][j]);
        }

        if (j < n) {// 往右走
            minDist(w, n, i, j+1, dist + w[i][j]);
        }
    }

    public static void main(String[] args) {
        int n = N;
//        int[][] w = {
//                {1,3,5,9,3,2,3,8,6,8},
//                {2,1,4,3,8,6,3,6,2,1},
//                {7,2,3,6,2,5,8,7,6,1},
//                {5,1,5,3,5,6,2,6,3,5},
//                {2,2,3,6,7,5,4,6,3,7},
//                {4,5,5,4,3,5,8,3,4,2},
//                {6,8,4,3,2,6,2,5,6,2},
//                {1,2,5,3,5,6,3,5,2,3},
//                {1,2,3,4,1,6,2,3,8,3},
//                {2,3,6,2,1,4,2,3,4,8}};
        int[][] w = new int[n][n];
        Random random = new Random(43);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                w[i][j] = random.nextInt(10);
            }
        }
        Solution2回溯法_状态表 solution回溯法 = new Solution2回溯法_状态表();
        long start = System.currentTimeMillis();
        solution回溯法.minDist(w, n-1, 0, 0, 0);
        long end = System.currentTimeMillis();
        System.out.println("最短距离: " + solution回溯法.min + ", 用时:[" + (end - start) + "ms]");
    }
}
